<template>
  <a-modal
    :visible="visible"
    okText="提交"
    cancelText="关闭"
    :title="title"
    :maskClosable="false"
    :keyboard="false"
    @cancel="closeModal()"
    @ok="handleSubmit"
  >
    <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
      <a-form-item label="字典名称">
        <a-input
          v-decorator="[
            'name',
            { rules: [{ required: true, message: '请填写字典名称' }] },
          ]"
          placeholder="请填写字典名称"
        />
      </a-form-item>
      <a-form-item label="字典值">
        <a-input
          v-decorator="[
            'dictValue',
            { rules: [{ required: true, message: '请输入字典值' }] },
          ]"
          placeholder="请输入字典值"
        />
      </a-form-item>
      <a-form-item label="字典类型">
        <a-select
          showSearch
          allowClear
          :options="typeOptions"
          v-decorator="[
            'type',
            { rules: [{ required: true, message: '请选择字典类型' }] },
          ]"
          placeholder="请选择字典类型"
        />
      </a-form-item>
      <a-form-item label="描述">
        <a-input v-decorator="['remark', {}]" placeholder="请填写描述" />
      </a-form-item>
      <a-form-item label="排序">
        <a-input-number
          :precision="0"
          :min="0"
          v-decorator="['sort', {}]"
          placeholder=""
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { findDictNameByValue, createOptionsByDict } from "@/utils/dict";

export default {
  name: "DictInfo",
  props: {
    record: {
      type: Object,
      default() {
        return {};
      },
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    title() {
      return this.record.id ? "修改字典" : "添加字典";
    },
  },
  data() {
    return {
      typeOptions: createOptionsByDict(1),
      form: this.$form.createForm(this, { name: "coordinated" }),
    };
  },
  watch: {
    visible(value) {
      if (value && this.record.id) {
        this.$nextTick(() => {
          const formItems = this.form.getFieldsValue();
          Object.keys(formItems).forEach((key) => {
            formItems[key] = this.record[key];
          });
          this.form.setFieldsValue(formItems);
        });
      }
    },
  },
  mounted() {},
  methods: {
    handleSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          let url = "/sys/dict";
          console.log(this.record);
          url = this.record.id ? `${url}/${this.record.id}/update` : url;
          this.$post(url, { ...values }).then((res) => {
            if (res && res.returnCode === 1000) {
              this.$message.success("保存成功！");
              this.closeModal(true);
            }
          });
        }
      });
    },

    closeModal(freshTable) {
      this.form.resetFields();
      this.$emit("cancel", freshTable);
    },
  },
};
</script>
